﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OC_Rep_ChronologicalAccountInterfaceBusiness : OCInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption OC_Query;
        //获取亚马逊店铺
        //public LX_SellerInterfaceBusiness sellerInterfaceBusiness;
        public OC_Rep_ChronologicalAccountInterfaceBusiness()
        {
            this.InterfaceName = "1C序时账";
            //索引字段
            this.MapFields = GetMapField("OZ_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            OC_Query = this.interfaceOption.Where(x => x.OperateType == "OC_Query").First();
            //获取亚马逊店铺
            //sellerInterfaceBusiness = new LX_SellerInterfaceBusiness();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="OZ_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, OC_NoQueryEventArgs OZ_NoQueryEventArgs)
        {
            //API请求是否成功
            OZ_NoQueryEventArgs.Success = OZ_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, OC_QueryEventArgs queryEventArgs)
        {
            try
            {
                //设置请求头参数
                var key = JObject.Parse(OC_Query.TargetLoginData);
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", key["Authorization"].Value<string>());
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                queryEventArgs.Page.Total = queryEventArgs.APINodes.Where(x => x.TargetField == "dateFrom").First().Notes.ToInt();
                //queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "pagesize").First().SourceField.ToInt();

            }
            catch (Exception ex)
            {

            }


        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, OC_QueryEventArgs queryEventArgs)
        {
            if (!queryEventArgs.UrlQuery.Header.IsNullOrEmpty())
            {
                //获取请求的数据
                OC_ReqDTO data = new OC_ReqDTO();
                data.dateFrom = DateTime.Now.AddMonths(-queryEventArgs.Page.Total).ToString("yyyy-MM")+"-01";//包含
                data.dateTo = DateTime.Now.ToString("yyyy-MM-dd");//不包含
                //data.pageIndex = queryEventArgs.Page.PageIndex;
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, OC_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                Rep_ChronologicalAccountDTO result = (Rep_ChronologicalAccountDTO)JsonConvert.DeserializeObject<Rep_ChronologicalAccountDTO>(queryEventArgs.ResultStr);
                result.rows.ForEach(r => r.id =(r.document + r.Amount + r.debitAccountingSubject + r.debitAnalytic1 + r.debitCount + r.creditAccountingSubject + r.creditAnalytic1 + r.creditCount).ToMD5String16()) ;

                if (result.success == true)
                {
                    //查询完成
                    queryEventArgs.Page.PageIndex = 0;
                    queryEventArgs.Page.Complete = true;
                    //查询数量小于单页最大数量查询完成
                    //if (result.rows.Count < queryEventArgs.Page.PageSize)
                    //{
                    //    //查询完成
                    //    queryEventArgs.Page.PageIndex = 0;
                    //    queryEventArgs.Page.Complete = true;
                        
                    //}
                    //else
                    //{
                    //    //查询下一页
                    //    queryEventArgs.Page.PageIndex += 1;

                    //}
                    queryEventArgs.Rows = result.rows;
                    queryEventArgs.Success = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<Rep_ChronologicalAccount> QQ = await this.QueryAsync<Rep_ChronologicalAccount>(this.OC_Query, SqlDb);
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
